var util = require('../../../../utils/util.js');
var api = require('../../../../config/api.js');
var lastTime = null;

Page({
  data: {
    id: '',
    bargain: {},
    mnmt_bargain: {},
    goods: {},
    fukucunsale: {},
    endTime: '3000-01-01 00:00:00',
    day: '00',
    hour: '00',
    minute: '00',
    second: '00',
    timeout: false,
    shouqing: false,
    jindu: 0,
    yikanzhi: 0,
    memberUserid: '',
    iszijikan: 0, //自己已砍则把值改成2,是否允许自己砍价 0.否 1.是 2.表示自己已经砍过用于控制自己砍一刀按钮的显示，为2时则不显示
    isyaoqing: false, //控制帮砍、我也要砍一件按钮，为true时则是通过邀请进来的，且为非分享人点击进来的。
    kanjiajilu: {}
  },

  // 获取商品信息
  getBargainDetail: function () {
    let that = this;
    util.request(api.BargainDetail, {
      pk_bargain: that.data.id
    }).then(function (res) {
      if (res) {
        if (res.result == 1) {
          that.setData({
            bargain: res.data.bargain,
            goods: res.data.goods,
            fukucunsale: res.data.fukucunsale,
            endTime: res.data.bargain.endTime,
          });
          if (res.data.goods.kucun <= 0) {
            that.setData({
              shouqing: true
            });
          }
        }
      }
    });
  },

  // 检查是否符合砍价条件,查看是否已开始了砍价,如果没有符合的砍价信息则重新创建砍价
  bargainxinxi: function () {
    let that = this;
    util.request(api.Bargainxinxi, {
      pk_bargain: that.data.id
    }).then(function (res) {
      if (res.result == 1) {
        //进度如果是超过一百则只显示100
        var _jindu = parseInt((res.data.mnMt_bargain.yikanrenshu / res.data.mnMt_bargain.bangkanrenshu) * 100);
        if (_jindu > 100) {
          _jindu = 100;
        }
        //已砍至价格低于底价则显示底价
        var _yikanzhi = res.data.mnMt_bargain.xiaoshoujia - res.data.mnMt_bargain.yikanjine;
        if (_yikanzhi < res.data.mnMt_bargain.dijia) {
          _yikanzhi = res.data.mnMt_bargain.dijia;
        }
        that.setData({
          mnmt_bargain: res.data.mnMt_bargain,
          iszijikan: res.data.mnMt_bargain.iszijikan,
          jindu: _jindu,
          yikanzhi: _yikanzhi.toFixed(2),
          endTime: res.data.mnMt_bargain.endTime
        })
        if (res.data.kanjiajilu) {
          that.setData({
            kanjiajilu: res.data.kanjiajilu
          })
        }
        that.countTime();
      }
      that.getBargainDetail();
    });
  },

  // 通过邀请砍价进入，且是分享人本人点击进入
  sharememkanjixinxi: function (pk_mn_mt_bargain) {
    let that = this;
    util.request(api.Bargainsharememkanjixinxi, {
      pk_mn_mt_bargain: pk_mn_mt_bargain
    }).then(function (res) {
      if (res.result == 1) {
        //进度如果是超过一百则只显示100
        var _jindu = parseInt((res.data.mnMt_bargain.yikanrenshu / res.data.mnMt_bargain.bangkanrenshu) * 100);
        if (_jindu > 100) {
          _jindu = 100;
        }
        //已砍至价格低于底价则显示底价
        var _yikanzhi = res.data.mnMt_bargain.xiaoshoujia - res.data.mnMt_bargain.yikanjine;
        if (_yikanzhi < res.data.mnMt_bargain.dijia) {
          _yikanzhi = res.data.mnMt_bargain.dijia;
        }
        that.setData({
          mnmt_bargain: res.data.mnMt_bargain,
          iszijikan: res.data.mnMt_bargain.iszijikan,
          jindu: _jindu,
          yikanzhi: _yikanzhi.toFixed(2),
          endTime: res.data.mnMt_bargain.endTime
        })
        if (res.data.kanjiajilu) {
          that.setData({
            kanjiajilu: res.data.kanjiajilu
          })
        }
        that.countTime();
      }
      that.getBargainDetail();
    });
  },

  // 页面分享
  onShareAppMessage: function (e) {
    let that = this;
    //邀请好友砍价
    return {
      title: that.data.goods.goodsname,
      desc: '好东西要一起分享！',
      path: '/pages/marketing/bargain/bargainDetail/bargainDetail?id=' + that.data.id + '&shareMemberUserid=' + that.data.memberUserid + '&pk_mn_mt_bargain=' + that.data.mnmt_bargain.id
    }
  },

  //自己砍一刀 iszijikan: 1代表自己砍
  zijikanyidao: function () {
    let that = this;
    if (that.data.bargain.kanjiakucun - that.data.bargain.yikankucun <= 0) {
      wx.showToast({
        title: '商品已被砍完！',
        icon: 'none'
      })
      return false;
    }

    util.request(api.Bargainbangkanyidao, {
      iszijikan: 1,
      pk_mn_bargain: that.data.mnmt_bargain.id
    }).then(function (res) {
      if (res.result == 1) {
        that.bargainxinxi();
        wx.showToast({
          title: "砍价成功！",
          duration: 1500
        });
      }
    });
  },

  //帮砍一刀 iszijikan: 0代表帮砍
  bangkanyidao: function () {
    let that = this;
    if (!that.data.mnmt_bargain.id) {
      wx.showToast({
        icon: 'error',
        title: "请关闭重进！",
        duration: 5000
      });
    }
    util.request(api.Bargainbangkanyidao, {
      iszijikan: 0,
      pk_mn_bargain: that.data.mnmt_bargain.id
    }).then(function (res) {
      if (res.result == 1) {
        that.sharememkanjixinxi(that.data.mnmt_bargain.id);
        wx.showToast({
          title: "砍价成功！",
          duration: 1500
        });
      }
    });
  },

  //我也要砍一件
  woyeyao: function () {
    let that = this;
    if (that.data.bargain.kanjiakucun - that.data.bargain.yikankucun <= 0) {
      wx.showToast({
        title: '商品已被砍完！',
        icon: 'none'
      })
      return false;
    }
    wx.navigateTo({
      url: '/pages/marketing/bargain/bargainList/bargainList'
    })
  },

  //砍价已结束后去看看
  qukankan: function () {
    let that = this;
    wx.navigateTo({
      url: '/pages/marketing/bargain/bargainList/bargainList'
    })
  },

  //立即购买（先自动加入购物车）
  buyadd: function () {
    var that = this;
    if (that.data.bargain.kanjiakucun - that.data.bargain.yikankucun <= 0) {
      wx.showToast({
        title: '商品已被砍完！',
        icon: 'none'
      })
      return false;
    }

    if (this.data.opendgg == false) {
      //打开规格选择窗口
      this.setData({
        opendgg: !this.data.opendgg
      });
    } else {
      util.jhxLoadShow("加载中...");
      let nowTime = +new Date();
      if (nowTime - lastTime > 5000 || !lastTime) { //5秒内避免重复提交订单
        lastTime = nowTime;
      } else {
        return false;
      }
      //立即购买
      util.request(api.MarketingShoppingCartBuyAdd, {
          number: 1,
          price: that.data.yikanzhi,
          pk_marketing: that.data.mnmt_bargain.id,
          tablename: "mn_mt_bargain",
        }, "POST")
        .then(function (res) {
          if (res.result == 1) {
            // 如果storage中设置了shoppingcartid，则是立即购买，否则是购物车购买
            wx.setStorageSync('shoppingcartid', res.data.shoppingcartid);
            wx.navigateTo({
              url: '/pages/marketing/mtorder/mtorder'
            })
          }
          else if(res.result == -4) {
            that.bargainxinxi();
          }
          else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: res.errmsg,
              mask: true
            });
          }
        });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    let that = this;
    if (options.id) {
      that.setData({
        id: options.id
      });
    }
    //获取该登录会员的缓存id
    let memberUserid = wx.getStorageSync('memberUserid');
    that.setData({
      memberUserid: memberUserid
    });
    //这个shareMemberUserid的存在证明是通过分享页面进来的
    if (options.shareMemberUserid) {
      if (memberUserid != options.shareMemberUserid) {
        that.setData({
          isyaoqing: true
        })
      }
      //通过邀请砍价进入时直接根据砍价pk查询砍价信息
      if (options.pk_mn_mt_bargain) {
        that.sharememkanjixinxi(options.pk_mn_mt_bargain);
      }
    } else {
      //非通过邀请砍价，本人进入查询砍价信息
      that.bargainxinxi();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  //倒计时
  countTime: function () {
    var that = this;
    var date = new Date();
    var now = date.getTime();
    var endDate = new Date(that.data.endTime); //设置截止时间
    var end = endDate.getTime();
    var leftTime = end - now; //时间差               
    var day, hour, minute, second;
    if (leftTime >= 0) {
      day = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      hour = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      minute = Math.floor(leftTime / 1000 / 60 % 60);
      second = Math.floor(leftTime / 1000 % 60);
      second = second < 10 ? "0" + second : second
      minute = minute < 10 ? "0" + minute : minute
      hour = hour < 10 ? "0" + hour : hour
      that.setData({
        hour: hour,
        minute: minute,
        second: second
      })
      if (day >= 99) {
        that.setData({
          day: 99
        })
      } else if (day === 0) {
        that.setData({
          day: '00'
        })
      } else {
        that.setData({
          day: day
        })
      }
      //递归每秒调用countTime方法，显示动态时间效果
      setTimeout(that.countTime, 1000);
    } else {
      that.setData({
        day: '00',
        hour: '00',
        minute: '00',
        second: '00',
        timeout: true
      })
    }
  }
})